const fs = require('fs')

let detail1 = fs.readFileSync('../package.json')

console.log(detail1.toString())

let detail2 = fs.readFile('../package.json', (error, data) => {
    console.log('data3 ++')
    console.log(data.toString())
})

console.log(detail2)

function my_async_function (name, fn) {
    setTimeout(() => {
        fn(null, `--${name}--`)
    }, 3000)
}

my_async_function('hello nodejs', (err, name) => {
    if (err) {
        console.log(err)
        returns
    }
    console.log(name)
})


class Eventes {
    constructor () {
        this.map = {}
    }

    add (name, fn) {
        if (this.map[name]) {
            this.map[name].push(fn)
            return
        }

        this.map[name] = [fn]
        return
    }

    emit (name, ...args) {
        console.log(this.map)
        this.map[name].forEach(fn => {
            fn(...args)
        })
    }
    
}

let e = new Eventes()

e.add('hello', (err, name) => {
    if (err) {
        console.error(err)
        return
    }
    console.log(name)
})

e.emit('hello', 'errors')

e.emit('hello', null, 'hello node.js')

class ChainEvents {
    constructor () {
        this.map = {}
    }

    add (name, fn) {
        if (this.map[name]) {
            this.map[name].push(fn)
            return
        }

        this.map[name] = [fn]
        return this
    }

    emit (name, ...args) {
        this.map[name].forEach(fn => fn(...args))

        return this
    }
}

let e2 = new ChainEvents()

e2.add('hello', (err, name) => {
    if (err) {
        console.error(err)
        return
    }

    console.log(name)
})
.emit('hello', 'error status')
.emit('hello', null, 'hello react')
